#include <iostream>
#include <string.h>
#include "message.h"
#include "types.h"

const uint32_t IMessage::SERIALIZED_MSG_HEADER_SIZE = 5;

class IMessage::IMessageImpl
{
public:
    MsgHead msgHead;
    bool serializeHeader(uint8_t **bufPtr) const
    {
        ValueToBuffer<uint8_t>(msgHead.src,     bufPtr);
        ValueToBuffer<uint8_t>(msgHead.dest,    bufPtr);
        ValueToBuffer<uint8_t>(msgHead.msgid,   bufPtr);
        ValueToBuffer<uint16_t>(msgHead.msglen, bufPtr);
        return true;
    }
    bool deserializeHeader(uint8_t **bufPtr)
    {
        ValueFromBuffer<uint8_t>(bufPtr,  msgHead.src);
        ValueFromBuffer<uint8_t>(bufPtr,  msgHead.dest);
        ValueFromBuffer<uint8_t>(bufPtr,  msgHead.msgid);
        ValueFromBuffer<uint16_t>(bufPtr, msgHead.msglen);
        return true;
    }
};

IMessage::IMessage(): m_pImpl(make_unique<IMessageImpl>())
{
    m_pImpl->msgHead.src    = 1;
    m_pImpl->msgHead.dest   = 2;
    m_pImpl->msgHead.msgid  = 1;
    m_pImpl->msgHead.msglen = SERIALIZED_MSG_HEADER_SIZE;
}

IMessage::~IMessage()
{

}

bool IMessage::serialize(uint32_t &size, uint8_t **buffer)
{
    uint8_t bufferSize = getBufferSize();
    uint8_t *bufPtr = new uint8_t[bufferSize];
    memset(bufPtr, 0, bufferSize);

    if (bufPtr == nullptr)
    {
        return false;
    }

    *buffer = bufPtr;
    size = bufferSize;
    m_pImpl->msgHead.msglen = size;

    // 序列化消息头
    m_pImpl->serializeHeader(&bufPtr);

    // 序列化消息内容
    serializeContent(&bufPtr);

    return true;
}

bool IMessage::deserialize(uint32_t size, uint8_t *buffer)
{
    m_pImpl->deserializeHeader(&buffer);

    deserializeContent(&buffer);

    return true;
}

void IMessage::setMsgId(uint8_t msgId)
{
    m_pImpl->msgHead.msgid = msgId;
}





